import { computed, ref } from "@vue/composition-api"

export function useTypeJudge(type) {
    const isLoading = computed(() => {
        if (type.value === 'loading') {
            return true
        }
        return false
    })
    const isCustom = computed(() => {
        if (type.value === 'custom') {
            return true
        }
        return false
    })
    return {
        isCustom,
        isLoading,
    }
}

export function usePublicApi() {
    const forbidClick = ref(false);
    const type = ref("message");
    const text = ref("");
    const visible = ref(false);
    const icon = ref('');

    let timer = ref(undefined)
    function initOptions(options) {
        const res = { ...options }
        if (!res.message) {
            res.message = ''
        }
        if (res.during === undefined) {
            res.during = 3000
        }
        res.forbidClick = !!res.forbidClick
        return res;
    }
    function up(options, setType) {
        const { during, message, forbidClick: fc, icon: ic } = initOptions(options)
        visible.value = true
        text.value = message
        forbidClick.value = fc
        icon.value = ic
        type.value = setType
        if (during !== 0) {
            timer.value = setTimeout(() => {
                clearTimeout(timer.value)
                timer.value = undefined
                visible.value = false
            }, during)
        }
    }
    function clear() {
        if (timer.value) {
            clearTimeout(timer.value)
        }
        timer.value = undefined
        visible.value = false
    }
    function message(options) {
        if (!visible.value) {
            up(options, 'message')
        }
    }

    function loading(options) {
        if (!visible.value) {
            up(options, 'loading')
        }
    }

    function custom(options) {
        if (!visible.value) {
            up(options, 'custom')
        }
    }

    return {
        loading,
        message,
        custom,
        clear,
        type, visible, text, forbidClick, icon,
    }
}